package com.study.demo_spring_security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: SecurityConfig
 * @Description: 单个HttpSecurity配置
 * @author: WS
 * @date 2020/12/27
 * @Version: 1.0
 **/
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder(){
//        return NoOpPasswordEncoder.getInstance();//密码不加密
        return new BCryptPasswordEncoder();//密码加盐加密
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("$2a$10$YfiyXSJfrK7YXDHljvNl1eR/yxKu6ODHgS8X.txzbi0KYr6ZOE3SG")
                .roles("admin")
                .and()
                .withUser("user")
                .password("$2a$10$KIq921wu3U5DKqnLoRT2EOqFgfG3n7jELhLJtf/ZO5pNWKfuVRD2.")
                .roles("user");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/system/**").permitAll()
                .antMatchers("/admin/**")
                .hasRole("admin")
                .antMatchers("/user/**")
                .hasAnyRole("admin","user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/doLogin")//处理登录的接口
                //.loginPage("/login")//登录页面
//                .usernameParameter("").passwordParameter("")//登录页面的参数
                .successHandler((req, resp, authentication) -> {
                    resp.setContentType("application/json;charset=utf8");
                    PrintWriter out = resp.getWriter();
                    out.print("登录成功");
                    Map<String,Object> map=new HashMap<>();
                    map.put("status","200");
                    map.put("msg",authentication.getPrincipal());
                    out.print(new ObjectMapper().writeValueAsString(map));
                    out.flush();
                    out.close();
                })
                .failureHandler((req, resp, e) -> {
                    resp.setContentType("application/json;charset=utf8");
                    PrintWriter out = resp.getWriter();
                    out.print("登录成功");
                    Map<String,Object> map=new HashMap<>();
                    map.put("status","401");
                    map.put("msg",e.getCause());
                    out.print(new ObjectMapper().writeValueAsString(map));
                    out.flush();
                    out.close();
                }).permitAll()
                .and()
                .logout()
                .logoutUrl("")
                .logoutSuccessHandler((request,response,authentication)->{})
                .and()
                .exceptionHandling().accessDeniedPage("/system/unauth")
                .and()
                .logout()
                .logoutUrl("/logout")
                .and()
                .csrf().disable();
    }
}
